package cn.edu.swu.cly.miniwebsvr.core;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class Router {//作用：远程调用功能，通过URL地址调用函数

    public void route(Parameter request, OutputStream response) {
        //参数回显：
        System.out.println("\n===== 新请求开始 =====");
        System.out.println("请求方法: " + request.getMethod()); // GET/POST
        System.out.println("请求URL: " + request.getUrl());     // /echo 或 /time
        System.out.println("URL参数（GET）: " + request.getUrlParams()); // ?name=test 解析结果
        System.out.println("Body参数（POST）: " + request.getBodyParams()); // POST表单参数
        System.out.println("所有参数: " + request.getAllParams()); // 合并后的参数
        System.out.println("===== 请求信息结束 =====\n");

        Config config = Config.getInstance();

        // TODO: 222024321072039/蔡礼洋 根据请求的URL获取Handler
        Handler handler = config.getHandler(request.getUrl());

        if (handler == null) {
            // 如果没有匹配的路由，使用 DefaultHandler 处理
            handler = config.getHandler("/");
        }

        if (handler != null) {
            handler.handle(request, response);
        } else {
            // TODO: 222024321072039/蔡礼洋 如果连DefaultHandler都没有，返回500 Internal Server Error
            String errorResponse = "HTTP/1.1 500 Internal Server Error\r\n" +
                    "Content-Type: text/html; charset=UTF-8\r\n" +
                    "Content-Length: 38\r\n" +
                    "Connection: close\r\n" +
                    "\r\n" +
                    "<h1>500 Internal Server Error</h1>";
            try {
                response.write(errorResponse.getBytes(StandardCharsets.UTF_8));
                response.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

